import { defineStore } from 'pinia'
import { computed, nextTick, ref } from 'vue'

export const useUserStore = defineStore('user', () => {

    const DEFAULT_USER_INFO = {
        face: '/static/user/default_avatar.png',
        name: '登录',
        uid: '点击登录享更多优质服务',
        isVip: 0,
    }

    const userInfo = ref(DEFAULT_USER_INFO)

    const token = ref('')

    const isLogin = computed(() => token.value.length !== 0)

    const setUserInfo = (data) => {
        userInfo.value = data
        uni.setStorageSync('user_info', data)
    }

    const setToken = (value) => {
        token.value = value
        uni.setStorageSync('token', value)

        if (value.length !== 0) {
            nextTick(() => {
                const pages = getCurrentPages()
                const page = pages.at(-1)
                page.$vm.onLogin && page.$vm.onLogin()
            })
        }
    }

    const fakeLogin = () => {
        setUserInfo({
            face: '/static/user/default_avatar.png',
            name: 'UZ_12345678',
            uid: 'ID :12345678',
            isVip: 1,
        })
        setToken('token')

        uni.$emit('toast', {
            message: '登录成功！！！'
        })
    }

    const loadFromStorage = () => {
        const info = uni.getStorageSync('user_info')
        if (info) userInfo.value = info

        const t = uni.getStorageSync('token')
        if (t) token.value = t
    }

    const logout = () => {
        setToken('')
        setUserInfo(DEFAULT_USER_INFO)

        uni.$emit('toast', {
            message: '已退出登录，2秒后返回首页'
        })

        setTimeout(() => {
            uni.reLaunch({
                url: '/pages/index/index',
            })
        }, 2000)
    }

    const init = () => {
        loadFromStorage()
    }

    return {
        userInfo,
        token,
        isLogin,
        setUserInfo,
        setToken,
        fakeLogin,
        loadFromStorage,
        init,
        logout,
    }
})